package thread.framepackage;

import java.util.concurrent.CountDownLatch;

/**
 * 控制多个线程 都 完成 某个方法， 主线程 再继续其他操作
 *
 * @author ch
 */
public class CountDownLatchT {
    private static final CountDownLatch latch = new CountDownLatch(3);

    public static void main(String[] args) {

        new Thread() {
            @Override
            public void run() {
                try {
                    System.out.println("子线程" + Thread.currentThread().getName() + "正在执行");
                    Thread.sleep(3000);
                    latch.countDown();
                    System.out.println("子线程" + Thread.currentThread().getName() + "执行完毕");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }.start();

        new Thread() {
            @Override
            public void run() {
                try {
                    System.out.println("子线程" + Thread.currentThread().getName() + "正在执行");
                    Thread.sleep(3000);
                    latch.countDown();
                    System.out.println("子线程" + Thread.currentThread().getName() + "执行完毕");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }.start();

        new Thread() {
            @Override
            public void run() {
                System.out.println("子线程" + Thread.currentThread().getName() + "正在执行");
                latch.countDown();
                System.out.println("子线程" + Thread.currentThread().getName() + "执行完毕");
            }
        }.start();

        System.out.println("----------");

        try {
            System.out.println("等待3个子线程执行完毕...");
            latch.await();
            System.out.println("3个子线程已经执行完毕");
            System.out.println("继续执行主线程");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}